package com.baoming.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.xwork.StringUtils;

public class LoginUtil {

	public static boolean checkNumber(HttpServletRequest request,
			String numberKey) {
		HttpSession session = request.getSession(false);
		if (session == null) {
			return false;
		}
		String check_number_key = (String) session.getAttribute("_CHECKCODE");
		if (StringUtils.isBlank(check_number_key)) {
			return false;
		}

		boolean b = check_number_key.equals(numberKey);
		request.getSession().removeAttribute("_CHECKCODE");

		return b;
	}

	public static void remeberMeByCookie(HttpServletRequest request,
			HttpServletResponse response, String name, String pwd,
			String remener) {

		if (remener == null) {
			return;
		}

		Cookie nameCookie = new Cookie("email", name);
		Cookie passwordCookie = new Cookie("password", pwd);

		nameCookie.setPath(request.getContextPath() + "/");
		passwordCookie.setPath(request.getContextPath() + "/");
		if (remener.equals("1")) {
			nameCookie.setMaxAge(7 * 24 * 60 * 60);
			passwordCookie.setMaxAge(7 * 24 * 60 * 60);
		} else {
			nameCookie.setMaxAge(0);
			passwordCookie.setMaxAge(0);
		}
		response.addCookie(nameCookie);
		response.addCookie(passwordCookie);
	}

	public static void checkCookies(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		String loginName = null;
		String loginPwd = null;
		if (cookies != null && cookies.length > 0) {
			for (Cookie c : cookies) {
				if (c.getName().equals("email")) {
					loginName = c.getValue();
				} else if (c.getName().equals("password")) {
					loginPwd = c.getValue();
				}
			}
		}
		if (loginName != null && loginPwd != null) {
			request.setAttribute("email", loginName);
			request.setAttribute("password", loginPwd);
			System.out.println("Im ok tool!");
		}
		
	}
}
